package com.ruoyi.purchase.service.impl;

import java.util.*;

import com.ruoyi.purchase.vo.PurchaseOrderPageVO;
import com.ruoyi.system.mapper.ItemsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.purchase.domain.PurchaseOrdersDetails;
import com.ruoyi.purchase.mapper.PurchaseOrdersMapper;
import com.ruoyi.purchase.domain.PurchaseOrders;
import com.ruoyi.purchase.service.IPurchaseOrdersService;

/**
 * 采购订单Service业务层处理
 *
 * @author ruoyi
 * @date 2025-10-20
 */
@Service
public class PurchaseOrdersServiceImpl implements IPurchaseOrdersService
{
    @Autowired
    private PurchaseOrdersMapper purchaseOrdersMapper;

    @Autowired
    private ItemsMapper itemsMapper;






    @Override
    public String generatePoId() {


        // 查询当前最大采购订单号
        String maxPoId = purchaseOrdersMapper.selectMaxPoId();
        if (maxPoId == null || maxPoId.isEmpty()) {
            return "CGDD000001";
        }

        // 提取数字部分并加1
        String numberPart = maxPoId.replace("CGDD", "");
        int nextNumber = Integer.parseInt(numberPart) + 1;

        // 格式化为6位数字
        return String.format("CGDD%06d", nextNumber);
    }

    /**
     * 新增采购订单和多条采购详情
     *
     * @param poId，itemId
     * @return PurchaseOrders
     */
    @Override
    @Transactional
    public int insertPurchaseOrderWithDetails(PurchaseOrders purchaseOrders) {

        purchaseOrders.setPoOrg("103");
        // 计算订单总数

        // 计算订单总数
        if (purchaseOrders.getPurchaseOrdersDetailsList() != null) {
            Long totalAmount = purchaseOrders.getPurchaseOrdersDetailsList().stream()
                    .mapToLong(PurchaseOrdersDetails::getPoNum)
                    .sum();
            purchaseOrders.setTotalAmount(totalAmount);
        }
        // 设置订单状态（新增时默认为0或其他您定义的初始状态）
        purchaseOrders.setPoStatus(0L);
        // 插入采购订单主表
        int result = purchaseOrdersMapper.insertPurchaseOrders(purchaseOrders);

        if(result>0 && purchaseOrders.getPurchaseOrdersDetailsList()!=null){
            for (PurchaseOrdersDetails purchaseOrdersDetails : purchaseOrders.getPurchaseOrdersDetailsList()) {
                purchaseOrdersDetails.setCodeNum(0L);
                purchaseOrdersDetails.setPoId(purchaseOrders.getPoId());
                purchaseOrdersDetails.setNotcodeNum(purchaseOrdersDetails.getPoNum());
                purchaseOrdersDetails.setPayoffNum(0L);
                purchaseOrdersDetails.setReceivedNum(0L);
                purchaseOrdersDetails.setReturnNum(0L);
                purchaseOrdersDetails.setReceivedStatus(0L);
                purchaseOrdersDetails.setRejectNum(0L);
                purchaseOrdersDetails.setCreatedPerson("采购张经理");
                purchaseOrdersDetails.setCreatedAt(purchaseOrders.getCreatedAt());
                purchaseOrdersDetails.setUpdatedAt(purchaseOrders.getUpdatedAt());

            }
            purchaseOrdersMapper.batchPurchaseOrdersDetails(purchaseOrders.getPurchaseOrdersDetailsList());
        }
        return result;


    }
    /**
     * 修改采购订单自动获取采购订单和采购订单单条信息
     *
     * @param poId，itemId
     * @return PurchaseOrders
     */
    public PurchaseOrders  getDetailByPoIdAndItemId(String poId, String itemId) {
        // 获取采购订单主表信息
        PurchaseOrders purchaseOrder = purchaseOrdersMapper.selectPurchaseOrdersById(poId);
        if (purchaseOrder != null) {
            // 获取特定的采购订单详情
            List<PurchaseOrdersDetails> detailsList = new ArrayList<>();
            PurchaseOrdersDetails detail = purchaseOrdersMapper.selectDetailByPoIdAndItemId(poId, itemId);
            if (detail != null) {
                detailsList.add(detail);
            }
            purchaseOrder.setPurchaseOrdersDetailsList(detailsList);
        }
        return purchaseOrder;
    }

    /**
     * 修改采购订单
     *
     * @param purchaseOrders 采购订单
     * @return 结果
     */
    @Transactional
    @Override
    public int updatePurchaseOrderWithDetails(PurchaseOrders purchaseOrders)
    {
        // 更新采购订单主表
        purchaseOrders.setUpdatedAt(new Date());
        int result = purchaseOrdersMapper.updatePurchaseOrders(purchaseOrders);
//        System.out.println("service处理后的采购订单主表"+purchaseOrders);
        // 更新采购订单详情
        if (result > 0 && purchaseOrders.getPurchaseOrdersDetailsList() != null
                && !purchaseOrders.getPurchaseOrdersDetailsList().isEmpty()) {

            PurchaseOrdersDetails detail = purchaseOrders.getPurchaseOrdersDetailsList().get(0);
            detail.setUpdatedAt(new Date());
            // 重新计算未打码数量
            if (detail.getPoNum() != null && detail.getCodeNum() != null) {
                detail.setNotcodeNum(detail.getPoNum() - detail.getCodeNum());
            }
//            System.out.println("service处理后的订单详情"+detail);
            result = purchaseOrdersMapper.updatePurchaseOrdersDetails(detail);
        }

        return result;
    }

    @Override
    public PurchaseOrderPageVO getDetailInfoByPoIdAndItemId(String poId, String itemId) {
        return purchaseOrdersMapper.selectDetaildataByPoIdAndItemId(poId,itemId);
    }

    /**
     * 采购订单页面列表数据
     *
     * @param
     * @return
     */
    @Override
    public List<PurchaseOrderPageVO> getPurchaseOrderPageList(PurchaseOrderPageVO purchaseOrderPageVO) {
        return purchaseOrdersMapper.selectPurchaseOrderPageList(purchaseOrderPageVO);
    }


    /**
     * 查询采购订单
     *
     * @param id 采购订单主键
     * @return 采购订单
     */
    @Override
    public PurchaseOrders selectPurchaseOrdersById(String id)
    {
        return purchaseOrdersMapper.selectPurchaseOrdersById(id);
    }

    /**
     * 查询采购订单列表
     *
     * @param purchaseOrders 采购订单
     * @return 采购订单
     */
    @Override
    public List<PurchaseOrders> selectPurchaseOrdersList(PurchaseOrders purchaseOrders)
    {
        return purchaseOrdersMapper.selectPurchaseOrdersList(purchaseOrders);
    }

    /**
     * 新增采购订单 旧已弃用 已更换名
//     *
//     * @param purchaseOrders 采购订单
//     * @return 结果
//     */
    @Transactional
    @Override
    public int insertPurchaseOrders(PurchaseOrders purchaseOrders)
    {
        int rows = purchaseOrdersMapper.insertPurchaseOrders(purchaseOrders);
        insertPurchaseOrdersDetails(purchaseOrders);
        return rows;
    }

    @Override
    public int updatePurchaseOrders(PurchaseOrders purchaseOrders) {
        return 0;
    }


    /**
     * 批量删除采购订单
     *
     * @param ids 需要删除的采购订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deletePurchaseOrdersByIds(Long [] ids)
    {
//        purchaseOrdersMapper.deletePurchaseOrdersDetailsByPoIds(ids);
//        return purchaseOrdersMapper.deletePurchaseOrdersByIds(ids);
        // 收集所有受影响的采购订单号
        Set<String> affectedPoIds = new HashSet<>();
        for (Long id : ids) {
            PurchaseOrdersDetails detail = purchaseOrdersMapper.selectPurchaseOrdersDetailsById(id);
            if (detail != null) {
                affectedPoIds.add(detail.getPoId());
            }
        }

        // 批量删除采购订单详情
        int result = purchaseOrdersMapper.deletePurchaseOrdersDetailsByPoIds(ids);

        // 检查每个受影响的采购订单是否还有详情，如果没有则删除
        if (result > 0) {
            for (String poId : affectedPoIds) {
                boolean hasDetails = hasPurchaseOrderDetails(poId);
                if (!hasDetails) {
                    purchaseOrdersMapper.deletePurchaseOrdersById(poId);
                }
            }
        }
        return result;
    }

    /**
     * 删除采购订单信息
     *
     * @param id 采购订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deletePurchaseOrdersById(Long  id)
    {

        // 先获取要删除的详情信息，获取采购订单号
        PurchaseOrdersDetails detail = purchaseOrdersMapper.selectPurchaseOrdersDetailsById(id);
        if (detail == null) {
            return 0;
        }

        String poId = detail.getPoId();

        // 删除采购订单详情
        int result = purchaseOrdersMapper.deletePurchaseOrdersDetailsByPoId(id);

        // 检查该采购订单是否还有详情，如果没有则删除采购订单主表
        if (result > 0) {
            boolean hasDetails = hasPurchaseOrderDetails(poId);
            if (!hasDetails) {
                purchaseOrdersMapper.deletePurchaseOrdersById(poId);
            }
        }
        return result;
    }

    /**
     * 新增采购订单信息 旧已弃用 已更换名
     *
     * @param purchaseOrders 采购订单对象
     */
    public void insertPurchaseOrdersDetails(PurchaseOrders purchaseOrders)
    {
        List<PurchaseOrdersDetails> purchaseOrdersDetailsList = purchaseOrders.getPurchaseOrdersDetailsList();
        Long id = purchaseOrders.getId();
        if (StringUtils.isNotNull(purchaseOrdersDetailsList))
        {
            List<PurchaseOrdersDetails> list = new ArrayList<PurchaseOrdersDetails>();
            for (PurchaseOrdersDetails purchaseOrdersDetails : purchaseOrdersDetailsList)
            {
                purchaseOrdersDetails.setPoId(String.valueOf(id));
                list.add(purchaseOrdersDetails);
            }
            if (list.size() > 0)
            {
                purchaseOrdersMapper.batchPurchaseOrdersDetails(list);
            }
        }
    }

    public boolean hasPurchaseOrderDetails(String poId) {
        int count = purchaseOrdersMapper.countPurchaseOrdersDetailsByPoId(poId);
        return count > 0;
    }


    public int deleteEmptyPurchaseOrders() {
        return purchaseOrdersMapper.deleteEmptyPurchaseOrders();
    }
}
